import os
import subprocess
import hashlib
import time
from openpyxl import Workbook

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SEND_DIR = os.path.join(BASE_DIR, '../senddata')
RECV_DIR = os.path.join(BASE_DIR, './udp_receiveddata')
SENDER = os.path.join(BASE_DIR, 'build/main_sender')
RECEIVER = os.path.join(BASE_DIR, 'build/main_receiver')
RESULT_XLSX = 'udp_result.xlsx'

# 获取所有bin文件
def get_bin_files(directory):
    return [f for f in os.listdir(directory) if f.endswith('.bin') and os.path.isfile(os.path.join(directory, f))]

def parse_loss_rate(output):
    for line in output.splitlines():
        if 'Packet loss rate:' in line:
            try:
                return float(line.split('Packet loss rate:')[1].replace('%','').strip())
            except:
                return None
    return None

def transfer_file(binfile):
    send_path = os.path.join(SEND_DIR, binfile)
    recv_path = os.path.join(RECV_DIR, binfile)
    # 启动接收端
    recv_proc = subprocess.Popen([RECEIVER, 'udp', '9001', recv_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    time.sleep(0.5)  # 确保接收端已监听
    # 启动发送端
    start = time.time()
    sender_proc = subprocess.run([SENDER, send_path, 'udp', '127.0.0.1', '9001'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    end = time.time()
    # 等待接收端结束
    recv_proc.wait(timeout=30)
    elapsed = end - start
    # 解析接收端输出获取丢包率
    receiver_stdout = recv_proc.stdout.read().decode(errors='ignore')
    loss_rate = parse_loss_rate(receiver_stdout)
    # 文件大小
    send_size = os.path.getsize(send_path) if os.path.exists(send_path) else 0
    recv_size = os.path.getsize(recv_path) if os.path.exists(recv_path) else 0
    # 速度（MB/s）
    mb = send_size / (1024 * 1024)
    mbps = mb / elapsed if elapsed > 0 else 0
    return [binfile, send_size, recv_size, f'{mbps:.3f}', f'{loss_rate:.2f}%' if loss_rate is not None else 'N/A']

def main():
    os.makedirs(RECV_DIR, exist_ok=True)
    files = get_bin_files(SEND_DIR)
    wb = Workbook()
    ws = wb.active
    ws.append(['文件名', '发送文件大小', '接收文件大小', '传输速度(MB/s)', '丢包率'])
    for f in files:
        print(f'UDP传输: {f}')
        result = transfer_file(f)
        ws.append(result)
        print(f'结果: {result}')
    wb.save(RESULT_XLSX)
    print(f'全部完成，结果已保存到 {RESULT_XLSX}')

if __name__ == '__main__':
    main() 